package com.lihan.services.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lihan.common.Result;
import com.lihan.common.SubmitResult;
import com.lihan.common.UserCodelRel;
import com.lihan.enums.MsgActionEnum;
import com.lihan.enums.MsgSignFlagEnum;
import com.lihan.enums.SearchFriendsStatusEnum;
import com.lihan.mapper.*;
import com.lihan.model.bo.UserBo;
import com.lihan.model.dto.LoginByPhoneForm;
import com.lihan.model.dto.MomentFormDTO;
import com.lihan.model.dto.UserLoginForm;
import com.lihan.model.vo.UserVo;
import com.lihan.netty.ChatMsg;
import com.lihan.netty.DataContent;
import com.lihan.netty.UserChannelRel;
import com.lihan.model.entity.FriendsRequest;
import com.lihan.model.entity.MyFriends;
import com.lihan.model.entity.User;
import com.lihan.services.IUserService;
import com.lihan.services.IUserService;
import com.lihan.services.IUserService;
import com.lihan.utils.*;
import com.lihan.model.vo.FriendsRequestVo;
import com.lihan.model.vo.MyFriendsVo;

import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.n3r.idworker.Sid;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * ClassName: UserServicesImpl
 * Package: com.lihan.services.impl
 * Description:
 *
 * @Author 李涵
 * @Create 2025-02-18 14:09
 * @Version 1.0
 */
@Service
@SuppressWarnings("all")
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    Sid sid;

    @Resource
    private UserMapper userMapper;

    @Resource
    private QRCodeUtils qrCodeUtils;

    @Resource
    private FastDFSClient fastDFSClient;

    @Resource
    private MyFriendsMapper myFriendsMapper;

    @Resource
    private FriendsRequestMapper friendRequestMapper;

    @Resource
    private UserMapperCustom userMapperCustom;

    @Resource
    private ChatMsgMapper chatMsgMapper;



    @Override
    public User getUserById(String id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public User getUserByUsername(String username) {

        User user = userMapper.selectByUsername(username);

        return user;
    }

    @Override
    public User updateUserInfo(User user) {
        userMapper.updateByPrimaryKeySelective(user);
        User userInfo = userMapper.selectByPrimaryKey(user.getId());
        return userInfo;
    }






    /**
     * @description 注册用户到数据库中
     */
    @Override
    public Result register(User userInfo) {
        // 基础的校验 + 处理注册的头像

        // 校验用户名是否唯一
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<User>().eq(User::getUsername, userInfo.getUsername()).or().eq(User::getPhone,userInfo.getPhone());
        int count = count(queryWrapper);
        if( count > 0) {
            return Result.errorMsg("该用户已被注册");
        }

        try {
            //生成唯一id
            String id = sid.nextShort();
            userInfo.setId(id);

            //对密码进行加密
            String pwd = MD5Utils.getPwd(userInfo.getPassword());
            userInfo.setPassword(pwd);

            //设置二维码
            String qrcodeUrl = getQrcodeUrl(userInfo);
            userInfo.setQrcode(qrcodeUrl);

            //设置头像
            String imageUrl = getImageUrl(userInfo);
            userInfo.setFaceImageBig(imageUrl);

            //设置头像缩略图
            String thump = "_150x150."; //缩略图后缀
            String[] arr = imageUrl.split("\\.");
            String thumpImgUrl = arr[0]+thump+arr[1];
            userInfo.setFaceImage(thumpImgUrl);

            //保存到数据库
            boolean flag = save(userInfo);

            if(flag){
                User user = getById(id);
                UserVo userVo = new UserVo();
                BeanUtils.copyProperties(user,userVo);
                return Result.ok(userVo);
            }

            return Result.errorMsg("错误！");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public Result login(UserLoginForm user) {
        //从用户表中查询用户，判断用户是否存在,用户存在就对密码进行校验,不存在就告知用户进行注册

        User userResult = getUserByUsername(user.getUsername());
        // 如果不存在自动注册，如果存在验证密码
        if(userResult!=null){
            //存在账号，验证密码是否正确
            if(!userResult.getPassword().equals(MD5Utils.getPwd(user.getPassword()))){
                return Result.errorMsg("密码不正确");
            }
        }else {
            //告知用户注册
            return Result.errorMsg("用户不存在，请注册！");
        }
        //返回Vo
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(userResult,userVo);

        return Result.ok(userVo);
    }

    @Override
    public Result loginByPhone(LoginByPhoneForm form) {

        if (StrUtil.isNotBlank(form.getCode())) {
            String code = UserCodelRel.get(form.getPhone());
            log.info(code);
            if(!form.getCode().equals(code)){
                return Result.errorMsg("验证码不正确");
            }
            //验证码正确
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,form.getPhone());
            User user = getOne(queryWrapper);
            //返回Vo
            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(user,userVo);

            return Result.ok(userVo);

        } else {
            // 查询数据库，看用户是否存在，不存在告知用户注册，存在调用api发送验证码到用户手机号
            QueryWrapper queryWrapper = new QueryWrapper<User>();
            queryWrapper.eq("phone", form.getPhone());
            int count = count(queryWrapper);
            if (count == 0) {
                return Result.errorMsg("用户未注册！");
            }
            //生成六位验证码
            String code = RandomUtil.randomNumbers(6);

            //调用api发送验证码
            SubmitResult submitResult = SendsmsUtil.sendCode(code, form.getPhone());

            if(submitResult.getCode() == 2){
                UserCodelRel.put(form.getPhone(),code);
                return Result.ok();
            }

            return Result.errorMsg("请重新发送验证码！");
        }
    }

    @Override
    public Result updateFaceImage(UserBo userBo){
        // 获取前传传过来的base64的字符串，然后转化位文件对象上传
        String base64Data = userBo.getFaceData();

        //定义一个图片的路径,并需要保持唯一性
        String userFacePath = "/usr/local/face/"+userBo.getUserId()+"userFaceBase64.png";
        //调用FileUtil中的类的方法将base64转化位文件对象
//        FileUtils.base64ToFile(userFacePath,userBo.getFaceData());
        String url;
        try {
            FileUtils.base64ToFile(userFacePath,base64Data);
            MultipartFile multipartFile = FileUtils.fileToMultipart(userFacePath);
            //获取fastDFS上传图片的路径
            url = fastDFSClient.uploadBase64(multipartFile);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        System.out.println(url);
        //拼接新城缩略图的路径
        if(StrUtil.isBlank(url)){
            return Result.errorMsg("更新头像失败");
        }
        String thump = "_150x150."; //缩略图后缀
        String[] arr = url.split("\\.");
        String thumpImgUrl = arr[0]+thump+arr[1];

        //更新用户头像
        User user = new User();
        user.setId(userBo.getUserId());
        user.setFaceImage(thumpImgUrl);
        user.setFaceImageBig(url);
        User userResult = updateUserInfo(user);
        return  Result.ok(userResult);
    }


    private String getQrcodeUrl(User userInfo) {
//        String qrCodePath ="/usr/local/qrcode/qrcode.png"; //必须要保证目录路径存在
        String qrCodePath ="E:\\user\\local\\qrcode\\qrcode.png"; //因为现在不在部署机上，需要模拟一下
        qrCodeUtils.createQRCode(qrCodePath,"bird-qrcode:" + userInfo.getUsername());

        //上传二维码到fastDFS并得到对应的url
        MultipartFile qrcodeFile = FileUtils.fileToMultipart(qrCodePath);
        String qrCodeURL = "`";
        try {
            qrCodeURL = fastDFSClient.uploadQRCode(qrcodeFile);
            System.err.println("图片的地址返回了吗" + qrCodeURL);
            return  qrCodeURL;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private String getImageUrl(User userInfo) throws Exception {
        //对头像进行处理
        //获取头像的base64编码
        String faceData = userInfo.getFaceData();
        //定义一个图片的路径,并需要保持唯一性
//        String userFacePath = "/usr/local/face/" + userInfo.getUsername() + "userFaceBase64.png";
        String userFacePath = "E:\\user\\local\\face\\"+ userInfo.getUsername() +"userFaceBase64.png"; //模拟

        //调用FileUtil中的类的方法将 base64转化位文件对象
        //FileUtils.base64ToFile(userFacePath,userBo.getFaceData());
        FileUtils.base64ToFile(userFacePath,faceData);

        MultipartFile multipartFile = FileUtils.fileToMultipart(userFacePath);

        //获取fastDFS上传图片的路径
        String url = fastDFSClient.uploadBase64(multipartFile);
        return url;
    }




}
